package cn.minhx.domain.activity.service.discount;

import cn.minhx.domain.activity.adapter.IActivityRepository;
import cn.minhx.domain.activity.model.valobj.DiscountTypeEnum;
import cn.minhx.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import jakarta.annotation.Resource;
import java.math.BigDecimal;
import org.apache.commons.lang3.StringUtils;

/**
 * 折扣计算
 *
 * @author min
 */
public abstract class AbstractDiscountCalculator implements IDiscountCalculator {

	@Resource
	protected IActivityRepository repository;

	protected static final BigDecimal MIN_PRICE = new BigDecimal("0.01");
	protected static final String SPLITTER = ",";

	@Override
	public BigDecimal calculate(String userId, BigDecimal originalPrice,
			GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount) {
		// 1. 人群标签过滤
		if (DiscountTypeEnum.TAG.equals(groupBuyDiscount.getDiscountType())) {
			boolean isCrowdRange = isCrowdRange(userId, groupBuyDiscount.getTagId());
			if (!isCrowdRange)
				return originalPrice;
		}
		// 2. 折扣优惠计算
		BigDecimal discountedPrice = doCalculate(originalPrice, groupBuyDiscount);
		// 判断折扣后金额，最低支付 MIN_PRICE
		if (discountedPrice.compareTo(BigDecimal.ZERO) <= 0) {
			return MIN_PRICE;
		}
		return discountedPrice;
	}

	// 人群过滤 - 限定人群优惠
	private boolean isCrowdRange(String userId, String tagId) {
		if (StringUtils.isBlank(tagId)) {
			return true;
		}
		return repository.withinCrowdTag(tagId, userId);
	}

	protected abstract BigDecimal doCalculate(BigDecimal originalPrice,
			GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount);
}
